// const reader = new FileReader()
// reader.readAsDataURL(file)
// reader.onload = () => ownerVm.callMethod(
// 	'receiveFile', {
// 		name: file.name,
// 		base64: reader.result
// 	}
// )

// renderJs input file 选择的文件转成Base64
export const fileToBase64 = (file) => { //将文件转场base64
	return new Promise((resolve, reject) => {
		const reader = new FileReader()
		reader.onloadend = () => {
			const base64String = reader.result
			let result = {
				path: base64String,
				size: file.size,
				name: file.name, //这个属性uni.chooseImage中没有
				type: file.type //这个属性uni.chooseImage中没有
			}
			resolve(result)
		}
		reader.onerror = () => {
			reject({
				mode: 'fileToBase64',
				data: {
					errMsg: 'File to base64 fail.'
				}
			})
		}
		reader.readAsDataURL(file)
	})
}

export const base64ToPath = (base64, name = '') => {
	return new Promise((r, j) => {
		if (typeof plus !== 'object') {
			return j(new Error('not support'))
		}
		var fileName = ''
		if (name) {
			const names = name.split('.')
			const extName = names.splice(-1)
			fileName = `${names.join('.')}-${getNewFileId()}.${extName}`
		} else {
			const names = base64.split(',')[0].match(/data\:\S+\/(\S+);/)
			if (!names) {
				j(new Error('base64 error'))
			}
			const extName = names[1]
			fileName = `${getNewFileId()}.${extName}`
		}
		var basePath = '_doc'
		var dirPath = 'uniapp_save'
		var filePath = `${basePath}/${dirPath}/${fileName}`
		if (
			!biggerThan(
				plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472',
				plus.runtime.innerVersion,
			)
		) {
			plus.io.resolveLocalFileSystemURL(
				basePath,
				function(entry) {
					entry.getDirectory(
						dirPath, {
							create: true,
							exclusive: false,
						},
						function(entry) {
							entry.getFile(
								fileName, {
									create: true,
									exclusive: false,
								},
								function(entry) {
									entry.createWriter(function(writer) {
										console.log('entry成功9999：' + filePath)
										console.log('toLocalURL', entry
											.toLocalURL())
										writer.onwrite = function() {
											// r(filePath)
											r(entry.toLocalURL())
										}
										writer.onerror = j
										writer.seek(0)
										writer.writeAsBinary(dataUrlToBase64(
											base64))
									}, j)
								},
								j,
							)
						},
						j,
					)
				},
				j,
			)
			return
		}
		var bitmap = new plus.nativeObj.Bitmap(fileName)
		bitmap.loadBase64Data(
			base64,
			function() {
				bitmap.save(
					filePath, {},
					function() {
						bitmap.clear()
						console.log('保存图片成功：' + filePath)
						r(filePath)
					},
					function(error) {
						bitmap.clear()
						j(error)
					},
				)
			},
			function(error) {
				bitmap.clear()
				j(error)
			},
		)
	})
}